package com.yawn.zddefect.util.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * <pre>
 * 富强 民主 文明 和谐
 * 自由 平等 公正 法治
 * 爱国 敬业 诚信 友善
 * </pre>
 *
 * @author yawn
 * @date 2018-03-13 15:19
 */
public class ThreadPool {

    private ExecutorService pool;

    public ThreadPool() {
    }

    public ThreadPool(ExecutorService pool) {
        this.pool = pool;
    }

    public void poolExecute(Runnable runnable) {
        getPool().submit(runnable);
    }

    public <V> V poolExecute(Callable<V> callable) {
        Future<V> future = getPool().submit(callable);
        V result = null;
        try {
            result = future.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public void shutdownPool() {
        if (this.pool != null && !this.pool.isShutdown()) {
            this.pool.shutdown();
        }
    }

    public ExecutorService getPool() {
        if (this.pool == null || this.pool.isShutdown() || this.pool.isTerminated()) {
            this.pool = Executors.newCachedThreadPool();
        }
        return this.pool;
    }

    public void setPool(ExecutorService pool) {
        shutdownPool();
        this.pool = pool;
    }
}
